﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IBatisNet.DataMapper;

namespace Yunzuan.Foundation.DataAccess
{
    /// <summary>
    /// 事务
    /// </summary>
    public class Transaction : DataContextBase, ITransaction
    {
        private static int transactionCount = 0;
        private static readonly object lockHelper = new object();
        bool flag = false; //是否自动回滚

        public static int GetTransactionCount()
        {
            return transactionCount;
        }

        /// <summary>
        /// 初始化Mapper
        /// </summary>
        public Transaction(string configName) : base(configName)
        {
            lock (lockHelper)
            {
                transactionCount++;
            }
            session = base.GetMapper().CreateSqlMapSession();
            session.BeginTransaction();
            mapper = session.SqlMapper;
        }

        /// <summary>
        /// 回滚事务
        /// </summary>
        public void RollBackTransaction()
        {
            if (!this.flag)
            {
                session.RollBackTransaction();
            }
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        /// <remarks>
        /// 失败时自动回滚
        /// </remarks>
        public void CommitTransaction()
        {
            CommitTransaction(true);
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        /// <param name="isFailAutoRollback">是否在失败时自动回滚</param>
        public void CommitTransaction(bool isFailAutoRollback)
        {
            try
            {
                session.CommitTransaction();
            }
            catch (Exception )
            {
                if (isFailAutoRollback)
                {
                    flag = true;
                    session.RollBackTransaction();
                }
                throw;
            }  
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            if (session != null)
            {
                session.CloseConnection();
                session.Complete();
                session = null;
            }
            lock (lockHelper)
            {
                transactionCount--;
            }
        }

    }
}
